<!--  update goods-->
<template>
  <div class="update-goods">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品修改</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图：修改主体 -->
    <el-card>
      <!-- 提示信息 -->
      <el-alert title="商品修改" type="info" center show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" :pace="200" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 竖直tan栏 -->
      <el-form
        :model="updateGoods.updateGoodsForm"
        :rules="updateGoods.updateGoodsFormRules"
        ref="updateGoodsRef"
        label-width="70px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          :stretch="true"
          v-model="activeIndex"
          :before-leave="beforeLeaveTab"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="updateGoods.updateGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格(元)" prop="goods_price">
              <el-input v-model="updateGoods.updateGoodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量(个)" prop="goods_number">
              <el-input v-model="updateGoods.updateGoodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量(g)" prop="goods_weight">
              <el-input v-model="updateGoods.updateGoodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="cate.cateIds"
                :clearable="true"
                :options="cate.cateList"
                :props="cate.casProps"
                @change="handleCasChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in cate.manyData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_valsChecked">
                <el-checkbox
                  :label="val"
                  v-for="(val, index) in item.attr_vals"
                  :key="index"
                  border
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in cate.onlyData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- 图片上传 -->
            <el-upload
              v-model="uploadPic.fileList"
              :action="uploadPic.url"
              :headers="uploadPic.header"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">上传图片</el-button>
              <div slot="tip" class="el-upload__tip">jpg/png files with a size less than 500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="updateGoods.updateGoodsForm.goods_introduce"></quill-editor>
            <el-button
              type="primary"
              @click="updateGoodsConfirm('updateGoodsRef')"
              class="addBtn"
            >修改商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览窗口 -->
    <el-dialog title="图片预览" :visible.sync="uploadPic.previewVisible" width="50%">
      <img :src="uploadPic.previewPath" alt class="preview-pic" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      goodsId: 0,
      activeIndex: '0',
      // 修改商品对象
      updateGoods: {
        // 修改商品表单数据
        updateGoodsForm: {
          goods_name: '',
          goods_price: 0,
          goods_number: 0,
          goods_weight: 0,
          goods_introduce: '',
          goods_cat: '',

          pics: [],
          attrs: []
        },
        updateGoodsFormRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' }
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' }
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ],
          goods_cat: [
            { required: true, message: '请输入商品重量', trigger: 'blur' }
          ]
        }
      },
      // 分类对象
      cate: {
        cateList: [],
        casProps: {
          value: 'cat_id',
          label: 'cat_name',
          children: 'children',
          expandTrigger: 'hover'
        },
        cateIds: [],
        manyData: [], // 动态参数列表数据
        onlyData: [] // 静态属性列表数据
      },
      // 图片上传对象
      uploadPic: {
        fileList: [],
        url: 'http://127.0.0.1:8888/api/private/v1/upload', // 上传图片后台地址
        header: {
          Authorization: sessionStorage.getItem('token')
        },
        previewPath: '', // 预览图片地址
        previewVisible: false // 控制预览图片窗口显示
      }
    }
  },

  created() {
    this.goodsId = this.$route.params.goodsId
    Promise.all([
      this.axios.get(`goods/${this.$route.params.goodsId}`),
      this.axios.get('categories')
    ]).then(result => {
      if (result[0].meta.status !== 200) {
        return this.$message.error('获取商品失败')
      }

      if (result[1].meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.updateGoods.updateGoodsForm.goods_name = result[0].data.goods_name
      this.updateGoods.updateGoodsForm.goods_price = result[0].data.goods_price
      this.updateGoods.updateGoodsForm.goods_number =
        result[0].data.goods_number
      this.updateGoods.updateGoodsForm.goods_weight =
        result[0].data.goods_weight
      this.updateGoods.updateGoodsForm.goods_introduce =
        result[0].data.goods_introduce
      this.updateGoods.updateGoodsForm.goods_cat = result[0].data.goods_cat
      this.updateGoods.updateGoodsForm.pics = result[0].data.pics
      this.updateGoods.updateGoodsForm.attrs = result[0].data.attrs
      this.cate.cateIds.push(result[0].data.cat_one_id)
      this.cate.cateIds.push(result[0].data.cat_two_id)
      this.cate.cateIds.push(result[0].data.cat_three_id)
      // this.cate.cateIds = result[0].data.goods_cat.split(',')
      result[0].data.pics.forEach(pic => {
        this.uploadPic.fileList.push({
          name: `image${pic.pics_id}.jpg`,
          url: pic.pics_sma_url
        })
      })
      result[0].data.attrs.forEach(attr => {
        if (attr.attr_sel === 'only') {
          this.cate.onlyData.push(attr)
        } else if (attr.attr_sel === 'many') {
          attr.attr_vals =
            attr.attr_vals.length === 0 ? [] : attr.attr_vals.split(',')
          attr.attr_valsChecked = [...attr.attr_vals]
          this.cate.manyData.push(attr)
        }
      })
      this.cate.cateList = result[1].data
    })
  },
  computed: {
    // 分类ID
    cateId() {
      if (this.cate.cateIds.length === 3) {
        return this.cate.cateIds[2]
      }

      return null
    }
  },

  methods: {
    // 根据商品ID查询商品
    queryGoodsById(goodsId) {
      this.axios.get(`goods/${goodsId}`).then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取商品失败')
        }

        this.updateGoods.updateGoodsForm.goods_name = resp.data.goods_name
        this.updateGoods.updateGoodsForm.goods_price = resp.data.goods_price
        this.updateGoods.updateGoodsForm.goods_number = resp.data.goods_number
        this.updateGoods.updateGoodsForm.goods_weight = resp.data.goods_weight
        this.updateGoods.updateGoodsForm.goods_introduce =
          resp.data.goods_introduce
        this.updateGoods.updateGoodsForm.goods_cat = resp.data.goods_cat
        this.updateGoods.updateGoodsForm.pics = resp.data.pics
        this.updateGoods.updateGoodsForm.attrs = resp.data.attrs
        this.cate.cateIds.push(resp.data.cat_one_id)
        this.cate.cateIds.push(resp.data.cat_two_id)
        this.cate.cateIds.push(resp.data.cat_three_id)
        // this.cate.cateIds = resp.data.goods_cat.split(',')
        resp.data.pics.forEach(pic => {
          this.uploadPic.fileList.push({
            name: `image${pic.pics_id}.jpg`,
            url: pic.pics_sma_rul
          })
        })
        resp.data.attrs.forEach(attr => {
          attr.attr_vals =
            attr.attr_vals.length === 0 ? [] : attr.attr_vals.split(',')
          attr.attr_valsChecked = [...attr.attr_vals]
          if (attr.attr_sel === 'only') {
            this.cate.onlyData.push(attr)
          } else {
            this.cate.manyData.push(attr)
          }
        })
      })
    },
    // 获取分类列表
    getCateList() {
      this.axios.get('categories').then(resp => {
        if (resp.meta.status !== 200) {
          return this.$message.error('获取商品分类列表失败')
        }
        this.cate.cateList1 = resp.data
      })
    },

    // 处理商品分类选择改变
    handleCasChange() {
      // this.updateGoods.updateGoodsForm.goods_cat = this.cate.cateIds.join(',')
      let pm1 = () => {
        return new Promise(resolve => {
          this.getParams()
          resolve()
        })
      }
      let pm2 = () => {
        return new Promise(resolve => {
          this.getAttrs()
          resolve()
        })
      }
      Promise.all([pm1(), pm2()]).then(() => {
        this.updateGoods.updateGoodsForm.attrs = this.cate.manyData.concat(
          this.cate.onlyData
        )
      })
    },
    // 离开第一项tab也前校验->分类项选择：已选，tab切换；未选，不执行切换
    beforeLeaveTab(activeName, oldActiveName) {
      if (
        oldActiveName === '0' &&
        this.updateGoods.updateGoodsForm.goods_cat === ''
      ) {
        this.$message.error('商品分类未选择')
        return false
      }
    },

    // 获取动态参数参数
    getParams() {
      this.axios
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('获取商品动态参数失败')
          }
          resp.data.forEach(item => {
            item.attr_vals =
              item.attr_vals === '' ? [] : item.attr_vals.split(',')
            item.attr_valsChecked = [...item.attr_vals]
          })

          this.cate.manyData = resp.data

          this.$message.success({
            message: '获取动态参数成功',
            duration: 500
          })
        })
    },
    // 获取静态属性
    getAttrs() {
      this.axios
        .get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        .then(resp => {
          if (resp.meta.status !== 200) {
            return this.$message.error('获取商品静态属性失败')
          }

          this.cate.onlyData = resp.data

          this.$message.success({
            message: '获取静态属性成功',
            duration: 500
          })
        })
    },
    // 处理文件预览
    handlePreview(pic) {
      // 获取预览图片地址
      this.uploadPic.previewPath = pic.response.data.url
      // 显示图片预览窗口
      this.uploadPic.previewVisible = true
    },
    // 处理文件移除
    handleRemove(pic) {
      // 获取移除图片临时路径
      const tmpPath = pic.response.data.tmp_path
      // 查找图片在提交表单图片数组pics中位置
      const index = this.updateGoods.updateGoodsForm.pics.findIndex(item => {
        return item.pic === tmpPath
      })
      // 调用splice函数删除该图片对象
      this.updateGoods.updateGoodsForm.pics.splice(index, 1)
    },
    // 处理成功上传图片
    handleSuccess(rep) {
      // 获取返回临时路径
      const tempPath = rep.data.tmp_path
      // 存入提交表单对象中
      this.updateGoods.updateGoodsForm.pics.push({ pic: tempPath })
    },
    // 修改商品确认
    updateGoodsConfirm(form) {
      // 校验表单
      this.$refs[form].validate(valid => {
        // 校验失败
        if (!valid) {
          return this.$message.error('修改商品表单项格式不正确，请重新修改')
        }
        // 校验成功
        // 发送修改请求
        this.axios
          .put(`goods/${this.goodsId}`, this.updateGoods.updateGoodsForm)
          .then(resp => {
            console.log(resp)
            if (resp.meta.status !== 200) {
              return this.$message.error('商品修改失败')
            }
            // 商品修改成功，跳转商品页面
            this.$router.push('/goods')
          })
      })
    }
  },

  components: {}
}
</script>

<style lang='scss' scoped>
.update-goods {
  .el-checkbox-group {
    // 复选框组复选框
    .el-checkbox {
      margin: 0;
    }
  }
  // 预览图片
  .preview-pic {
    width: 100%;
  }
  // 修改按钮
  .addBtn {
    margin-top: 15px;
  }
}
</style>
